package com.sbootv.sys.shiro;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.sbootv.sys.mapper.SysUserMapper;
import com.sbootv.sys.pojo.SysUser;

public class UserRealm extends AuthorizingRealm {
	
	@Autowired
	private SysUserMapper userMapper;

	/**
	 * 验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken)token;
		String username = upToken.getUsername();
		String password = String.valueOf(upToken.getPassword());
		Map<String, Object> map  = new HashMap<String,Object>();
		map.put("username", username);

		// 查询用户信息
		SysUser user = null;
		List<SysUser> userList = userMapper.list(map);
		if(userList.size()!=0){
			user = userList.get(0);
		}
		
		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException("账号不存在！");
		}

		// 密码错误
		if (!password.equals(user.getPassword())) {
			throw new IncorrectCredentialsException("密码错误！");
		}

		// 账号锁定
		if ("0".equals(user.getState())) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
		return info;
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		return null;
	}
}
